import Seo from "@/core/components/Seo"
import { getIdFromSlug } from "@/core/utils/slug"
import productApi from "@/lib/product/api/productApi"
import dynamic from "next/dynamic"

const BasicLayout = dynamic(() => import("@/core/components/layouts/BasicLayout"))
const Product = dynamic(() => import("@/lib/product/components/Product"))

export async function getServerSideProps(context) {
  const { slug } = context.query
  let product = await productApi({ id: getIdFromSlug(slug) })
  if (product?.length == 1) {
    product = product[0]
    product.description = product.description.replaceAll('<p>', '||p||')
    product.description = product.description.replaceAll('</p>', '||/p||')
    product.description = product.description.replace(/(<([^>]+)>)/gi, ' ')
    product.description = product.description.replaceAll('||p||', '<p>')
    product.description = product.description.replaceAll('||/p||', '</p>')
    product.description = product.description.trim()
  }
  return { props: { product } }
}

export default function ProductDetail({ product }) {
  return (
    <BasicLayout>
      <Seo title={product?.name} />
      <Product product={product} />
    </BasicLayout>
  )
}